﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Lucene.Net.Documents;
using System.Linq;

//TODO: connect psichatinfos
//TODO: consider updates to history files
//TODO: make dir configurable or discover it
//TODO: interface for parser??
//TODO: GUI ;-)

namespace PsiIndexer
{
  internal class Program
  {
    private static void Main(string[] args)
    {
      string dir = @"c:\Users\skraemer\PsiData\profiles\default\history\";
      string dirArg = args.FirstOrDefault();
      if(!string.IsNullOrEmpty(dirArg) && Directory.Exists(dirArg)) {
        dir = dirArg;
      }

      PsiIndexer pi = PsiIndexer.Create(dir, true, false, null);

      string searchTerm = null;
      while (searchTerm == null || searchTerm.Length > 0) {
        Console.Write("enter search: ");
        searchTerm = Console.ReadLine();
        if (string.IsNullOrEmpty(searchTerm)) {
          return;
        }
        var searchResult = pi.LuceneIndexer.Search(searchTerm, 10);
        WriteToConsole(searchResult);
        Console.WriteLine();
        Console.WriteLine();
      }
    }

    public static void WriteToConsole(SearchResult sr)
    {
      if (sr != null && sr.Success) {
        Console.WriteLine("Found " + sr.Hits.Count() + " hits. In {0}ms", sr.DurationInMS);
        int i=0;
        foreach (Document d in sr.Hits) {
          string text = d.Get(LuceneMagicStrings.Text);
          string author = d.Get(LuceneMagicStrings.Author);
          string time = d.Get(LuceneMagicStrings.Time);
          string file = d.Get(LuceneMagicStrings.File);
          string dir = d.Get(LuceneMagicStrings.Direction);
          "{0} {1} {2} ".ToConsole(ConsoleColor.White, (i + 1).ToString(), time, dir);
          "{0}: ".ToConsole(ConsoleColor.Gray, author);
          "{0}".ToConsoleNewLine(ConsoleColor.Yellow, text);
          i++;
        }
      }
      else {
        Console.WriteLine("Query failed because of: {0}", sr.Error);
      }
    }

    private static void fsw_Changed(object sender, FileSystemEventArgs e)
    {
      e.FullPath.ToString();
    }
  }
}